package org.nobject.common.db.member;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.nobject.common.lang.ListUtils;

/**
 * SqlGroup
 *
 * @author bianrongjun
 * @version 1.0
 */
public class SqlGroup {

	/** 字段 */
	private List<String> groups = null;
	/** 表别名 */
	private String tableName = null;
	
	/** 构造 */
	public SqlGroup() {groups = new LinkedList<String>();}
	/** 构造函数 */
	public SqlGroup(List groups) {this.groups=groups;}
	/** 构造函数  */
	public SqlGroup(String[] groups){this.groups=ListUtils.toList(groups);}
	
	/** 添加 */
	public SqlGroup add(String columnName) {groups.add(columnName);return this;}
	/** 设置表别名 */
	public SqlGroup setTabName(String tabName) {this.tableName = tabName;return this;}
	/** 得到groupBy语句 */
	public String getSql() {
		StringBuffer sb = new StringBuffer();
		for (Iterator iterator = this.groups.iterator(); iterator.hasNext();) {
			if (this.tableName != null) sb.append(this.tableName).append(".");
			String column = (String) iterator.next();
			sb.append(column);
			if (iterator.hasNext()) sb.append(",");
		}
		return sb.toString();
	}
	
	/** 得到groupBy语句 */
	public String getSql(Map<String,String> reflectTabColumns) {
		StringBuffer sb = new StringBuffer();
		for (Iterator iterator = this.groups.iterator(); iterator.hasNext();) {
			String column = (String) iterator.next();
			if(reflectTabColumns.containsKey(column)) sb.append(reflectTabColumns.get(column)).append(".");
			sb.append(column);
			if (iterator.hasNext()) sb.append(",");
		}
		return sb.toString();
	}
	
	/** 得到groupBy语句 */
	public String getSql(String tableName) {this.tableName=tableName;return getSql();}
	/** 判断groupBy元素是否为空 */
	public boolean empty() {return (groups == null || groups.size() == 0);}
}
